<?php


namespace App\Service\Weapp;


use App\Service\Http\HttpInterface;


class App implements WeappInterface
{

    private $appid;

    private $secret;

    /**
     * @var HttpInterface
     */
    private $http;


    private $result;

    /**
     * App constructor.
     * @param $appid
     * @param $secret
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    function __construct($appid, $secret)
    {
        $this->appid = $appid;

        $this->secret = $secret;

        $this->http = app()->make(HttpInterface::class);
    }


    /**
     * Create by Peter
     * 2019/10/12 11:09:59
     * Email:904801074@qq.com
     * @param string $code
     * @return WeappInterface
     */
    public function setSession(string $code)
    {
        // TODO: Implement getSession() method.

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->appid . '&secret=' . $this->secret . '&js_code=' . $code . '&grant_type=authorization_code';

        $result = $this->http->get($url);

        $result=json_decode($result,true);

        $openid=$result['openid'];

        \Cache::put('weapp_session_'.$openid,$result['session_key']);




        return $openid;

//        return $this;
    }

    function getSession($openid):string {

        return \Cache::get('weapp_session_'.$openid);
    }


    public function getAccessToken(): string
    {

        // TODO: Implement getAccessToken() method.

        if (\Cache::has('weapp_access_token')) return \Cache::get('weapp_access_token');

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}";

        $result = $this->http->get($url);

        $result = json_decode($result, true)['access_token'];

        $this->result = $result;

        \Cache::put('weapp_access_token', $result, 6000);

        return $result;


    }

    public function getUnionId(string $openid): WeappInterface
    {
        // TODO: Implement getUnionId() method.

        $url = "https://api.weixin.qq.com/wxa/getpaidunionid?access_token={$this->getAccessToken()}&openid=" . $openid;

        $this->result = $this->http->get($url);

        return $this;

    }


    function __toString()
    {

        return (string)$this->result;
    }

    public function toArray(): array
    {
        // TODO: Implement toArray() method.


        return json_decode($this->result, true);
    }


    /**
     * 解密
     * Create by Peter
     * 2019/09/19 09:14:46
     * Email:904801074@qq.com
     * @param $encryptedData
     * @param $iv
     * @param $sessionKey
     * @return mixed|string
     * @throws \Exception
     */
    public function decrypt($encryptedData, $iv, $sessionKey)
    {
        // TODO: Implement decrypt() method.


        if (strlen($sessionKey) != 24) throw new \Exception('sessionKey长度不够！');

        $aesKey = base64_decode($sessionKey);

        if (strlen($iv) != 24) throw new \Exception('iv长度不够！');

        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);

        if ($dataObj == NULL) throw new \Exception('解密错误！');

        if ($dataObj->watermark->appid != $this->appid) throw new \Exception('appid异常');

        return $result;

    }

    /**
     * 解密
     * Create by Peter
     * 2019/09/19 09:14:46
     * Email:904801074@qq.com
     * @param $encryptedData
     * @param $iv
     * @param $sessionKey
     * @return mixed|string
     * @throws \Exception
     */
    public function decryptArray($encryptedData, $iv, $sessionKey)
    {
        // TODO: Implement decrypt() method.


        if (strlen($sessionKey) != 24) throw new \Exception('sessionKey长度不够！');

        $aesKey = base64_decode($sessionKey);

        if (strlen($iv) != 24) throw new \Exception('iv长度不够！');

        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result,true);

        if (!is_array($dataObj)) throw new \Exception('解密错误！');

//        if ($dataObj->watermark->appid != $this->appid) throw new \Exception('appid异常');
        if ($dataObj['watermark']['appid'] != $this->appid) throw new \Exception('appid异常');

        return $dataObj;

    }


    /**
     * 获取sessionKey、openid等信息
     * Create by Peter
     * 2019/12/04 16:18:36
     * Email:904801074@qq.com
     * @param $code
     * @return array
     */
    public function requestSessionKey($code): array
    {
        // TODO: Implement requestSessionKey() method.

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->appid . '&secret=' . $this->secret . '&js_code=' . $code . '&grant_type=authorization_code';

        $result = $this->http->get($url);

        $result=json_decode($result,true);

        return  $result;


    }
}
